const AElfModule = require('../models/aelf')
const PkManageModule = require('../models/private_key_manage')
const HistoryModule = require('../models/history')

exports.form = (req, res) => {
    res.render('cr_transfer', { title: '版权转让' });
};

exports.transfer = (req, res) => {
    const data = req.body;
    const aelf = new AElfModule();
    console.log(data);
    var log = new HistoryModule(data.owner);
    PkManageModule.get_priKey_by_user(data.account, (buyer)=>{
        aelf.check_chain_state((state) => {
            if (state) {
                aelf.load_wallet(buyer.priKey, (wallet1) => {
                    if (typeof (wallet1) !== 'undefined') {
                        aelf.load_contract(false, (param) => {
                            console.log("contract prepared");
                            aelf.approve(param, data.price, (res) =>{
        PkManageModule.get_priKey_by_user(data.owner, (owner)=>{
            aelf.load_wallet(owner.priKey, (wallet) => {
                if (typeof (wallet) !== 'undefined') {
                    aelf.load_contract(true, (param1) => {
                        console.log("contract prepared");
                        aelf.CR_Transfer(param1, wallet1.address, data.price, data.CR_tid, (ret)=>{
                            log.Log(ret['TransactionId'])
                        }
                    );
                });
            }
        });
                                });
                            });
                        });
                    }
                });
            }
        })
    })

    res.redirect('back');


}